<template>
  <text class="text-28" :class="[canGetCode?'color-primary':'color-grey']" @click="getCode">{{ codeText }}</text>
</template>

<script setup lang="ts">
import { mobile } from '@/common/test'
import { toast } from '@/common/util'
import { sendMsg } from '@/common/api'

interface IProps{
  phone: string
}

const props = withDefaults(defineProps<IProps>(), {
  phone: ''
})

const codeText = ref('获取验证码')
const canGetCode = ref(true)
async function getCode() {
  if (canGetCode.value) {
    if (!mobile(props.phone)) {
      toast('请输入正确的手机号')
      return
    }
    canGetCode.value = false

    let num = 60
    codeText.value = `重新获取（${num}）`
    let timer = setInterval(() => {
      num--
      codeText.value = `重新获取（${num}）`
      if (num <= 0) {
        codeText.value = '获取验证码'
        canGetCode.value = true
        clearInterval(timer)
        timer = 0
      }
    }, 1000)

    const res = await sendMsg({
      tel: props.phone
    })
    toast('获取验证码成功')
  }
}
</script>

<style scoped>
</style>
